/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.aternity.vbd.ui;

import com.aternity.vbd.collect.ActivityData;
import com.aternity.vbd.collect.ApplicationDao;
import com.aternity.vbd.collect.ApplicationsData;
import com.aternity.vbd.collect.feedback.FeedbackData;
import dnl.utils.swing.OkDialog;
import org.joda.time.DateTime;

import java.util.*;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.event.ListDataListener;

/**
 * @author Daniel Orr
 */
public class FeedbackEditingDialog extends OkDialog {

    private FeedbackData feedbackData;
    private ApplicationDao applicationDao;

    ApplicationsData applicationsAndActivities;

    /**
     * Creates new form InsertFeedbackDialog
     */
    public FeedbackEditingDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public void setApplicationDao(ApplicationDao applicationDao) {
        this.applicationDao = applicationDao;
    }

    public void refreshData() {
        applicationsAndActivities = applicationDao.getApplicationsAndActivities();
        final Set<String> appNames = applicationsAndActivities.getAppNames();
        appCombo.setModel(new DefaultComboBoxModel(appNames.toArray(new String[appNames.size()])));
        refreshActivityCombo();
    }

    public void setFeedbackData(FeedbackData feedbackData) {
        DateTime dt = new DateTime(feedbackData.getStartTime());

        this.feedbackData = feedbackData;
        setStartTime(feedbackData.getStartTime());
        setEndTime(feedbackData.getEndTime());
        appCombo.setSelectedItem(feedbackData.getApp());
        ActivityData ad = applicationsAndActivities.getActivityDataById(feedbackData.getActivityId());
        activityCombo.setSelectedItem(ad);
        problemCB.setSelected(feedbackData.isProblem());
        commentTA.setText(feedbackData.getComment());
    }

    public FeedbackData getFeedbackData() {
        if (feedbackData == null) {
            feedbackData = new FeedbackData();
        }
        final ActivityComboModel activityComboModel = (ActivityComboModel) activityCombo.getModel();
        feedbackData.setActivity(activityComboModel.getSelectedActivityData().getActivityName());
        feedbackData.setActivityId(activityComboModel.getSelectedActivityData().getActivityId());
        feedbackData.setStartTime(getStartTime());
        feedbackData.setEndTime(getEndTime());
        feedbackData.setApp(appCombo.getSelectedItem().toString());
        feedbackData.setComment(commentTA.getText());
        feedbackData.setProblem(problemCB.isSelected());
        return feedbackData;
    }

    private Date getStartTime() {
        return new Date(fromDatePicker.getDate().getTime() + fromHourPicker.getTimeMillis());
    }

    private Date getEndTime() {
        return new Date(toDatePicker.getDate().getTime() + toHourPicker.getTimeMillis());
    }

    private void setStartTime(Date d) {
        DateTime dt = new DateTime(d);
        DateTime startOfDay = dt.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
        fromDatePicker.setDate(startOfDay.toDate());
        fromHourPicker.setHourPart(dt.getHourOfDay());
        fromHourPicker.setMinutesPart(dt.getMinuteOfHour());
    }

    private void setEndTime(Date d) {
        DateTime dt = new DateTime(d);
        DateTime startOfDay = dt.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
        toDatePicker.setDate(startOfDay.toDate());
        toHourPicker.setHourPart(dt.getHourOfDay());
        toHourPicker.setMinutesPart(dt.getMinuteOfHour());
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this
     * code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        fromDatePicker = new org.jdesktop.swingx.JXDatePicker();
        toDatePicker = new org.jdesktop.swingx.JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        fromHourPicker = new com.aternity.vbd.ui.HourPicker();
        toHourPicker = new com.aternity.vbd.ui.HourPicker();
        problemCB = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        commentTA = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        appCombo = new javax.swing.JComboBox();
        activityCombo = new JComboBox<ActivityData>()
        ;

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Time Range"));

        jLabel1.setText("From:");

        jLabel2.setText("To:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(fromDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fromHourPicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel2)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(toDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(toHourPicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(50, 50, 50))
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel1)
                                        .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(fromDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(toDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(fromHourPicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(toHourPicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(30, Short.MAX_VALUE))
        );

        problemCB.setText("Problem");

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder("Comment"));

        commentTA.setColumns(20);
        commentTA.setRows(5);
        jScrollPane1.setViewportView(commentTA);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("App Data"));

        jLabel3.setText("App:");

        jLabel4.setText("Activity:");

        appCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                appComboActionPerformed(evt);
            }
        });

        activityCombo.setToolTipText("Shows activity name and ID");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel3)
                                        .addComponent(appCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(46, 46, 46)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel4)
                                        .addComponent(activityCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(27, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(22, 22, 22)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel3)
                                        .addComponent(jLabel4))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(appCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(activityCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap(18, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(problemCB)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(22, 22, 22)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(64, 64, 64)
                                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(problemCB)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void appComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_appComboActionPerformed
        refreshActivityCombo();
    }//GEN-LAST:event_appComboActionPerformed

    private void refreshActivityCombo() {
        final String selectedApp = (String) appCombo.getSelectedItem();
        if (selectedApp != null) {
            final Collection<ActivityData> activityData = applicationsAndActivities.getActivityData(selectedApp);
            activityCombo.setModel(new ActivityComboModel(activityData));
            activityCombo.setSelectedIndex(0);
        }
    }

    private static class ActivityComboModel implements ComboBoxModel<ActivityData> {

        private List<ActivityData> data;

        private ActivityData selectedItem;

        private ActivityComboModel(Collection<ActivityData> data) {
            this.data = new ArrayList<>(data);
            Collections.sort(this.data, new Comparator<ActivityData>() {
                @Override
                public int compare(ActivityData ad1, ActivityData ad2) {
                    return ad1.getActivityName().compareTo(ad2.getActivityName());
                }
            });
        }

        @Override
        public void setSelectedItem(Object anItem) {
            selectedItem = (ActivityData) anItem;
        }

        @Override
        public Object getSelectedItem() {
            return selectedItem;
        }

        public ActivityData getSelectedActivityData() {
            return selectedItem;
        }

        @Override
        public int getSize() {
            return data.size();
        }

        @Override
        public ActivityData getElementAt(int index) {
            return data.get(index);
        }

        @Override
        public void addListDataListener(ListDataListener l) {
        }

        @Override
        public void removeListDataListener(ListDataListener l) {
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FeedbackEditingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FeedbackEditingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FeedbackEditingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FeedbackEditingDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FeedbackEditingDialog dialog = new FeedbackEditingDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox<ActivityData> activityCombo;
    private javax.swing.JComboBox appCombo;
    private javax.swing.JTextArea commentTA;
    private org.jdesktop.swingx.JXDatePicker fromDatePicker;
    private com.aternity.vbd.ui.HourPicker fromHourPicker;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox problemCB;
    private org.jdesktop.swingx.JXDatePicker toDatePicker;
    private com.aternity.vbd.ui.HourPicker toHourPicker;
    // End of variables declaration//GEN-END:variables
}
